<template>
  <div class="echartsLine_container">
    <div class="filters">
      <span class="filter_text">
        {{ currentDateText }}<template v-if="chartData.seriesData.length === 1">指标</template
        ><template v-if="chartData.seriesData.length > 1">指标同比</template>趋势
      </span>
      <van-button class="filter_btn" type="primary" size="small" @click="openPicker">
        {{ currentDateText }}
        <svg-icon icon="dropDown"></svg-icon>
      </van-button>
    </div>
    <div class="chart_wrapper" v-show="!noData">
      <div id="line-chart" ref="chart" class="chart_container"></div>
    </div>
    <!-- <no-data style="padding-top: 0;" :desc="noDataText" v-show="noData"></no-data> -->
    <div v-show="noData" class="no-data">
      <svg-icon icon="noData" style="margin-right: 5px"></svg-icon>&nbsp;
      {{ noDataText }}
    </div>
    <div class="baseDataline"></div>
    <van-popup v-model="showPicker" round position="bottom">
      <van-picker
        title="选择时间范围"
        show-toolbar
        :columns="dateColumns"
        confirm-button-text="确定"
        value-key="text"
        @confirm="onConfirm"
        @cancel="onCancel"
      />
    </van-popup>
  </div>
</template>

<script>
/* eslint-disable */
import * as _ from 'lodash'
import * as echarts from 'echarts/core'
import { TitleComponent, TooltipComponent, GridComponent, LegendComponent } from 'echarts/components'
import { LineChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'
import { dataFormatWidthUnitLevel, dataFormat, getUnitFromLevel } from '@/filters/filter'
import NoData from '@/components/NoData'
echarts.use([TitleComponent, TooltipComponent, GridComponent, LegendComponent, LineChart, CanvasRenderer])
const dateColumns = [
  { text: '近一年', code: 'year' },
  { text: '近一个月', code: 'month' },
  { text: '近7天', code: 'day' }
]
const baseYAxisConfig = {
  type: 'value',
  // min: 0,
  // max: 0,
  // interval: 5,
  scale: true,
  axisLabel: {
    textStyle: {
      show: true,
      color: '#D5D5D8',
      fontSize: '12'
    },
    formatter: '{value}'
  },
  splitLine: {
    lineStyle: {
      type: 'dashed',
      color: '#363A46'
    }
  },
  // axisLine: {
  //   onZero: false
  // }
}
export default {
  props: ['xAxis', 'data', 'unitLevel', 'dateType'],
  components: { NoData },
  data() {
    return {
      showPicker: false,
      dateColumns,
      // currentDate: this.dateType,
      noDataText: '无数据',
      lineChart: null
    }
  },
  mounted() {
    this.initChat()
  },
  methods: {
    onConfirm(value) {
      this.currentDate = value.code
      this.$emit('dateChange', value.code)
      this.closePicker()
    },
    onCancel() {
      this.closePicker()
    },
    disposeEcharts() {
      if (this.lineChart) {
        echarts.dispose(this.lineChart)
      }
    },
    pulsMaxValue(unit, type, value) {
      if (type === 'number') {
        return value + 10 * unit
      } else if (type === 'person') {
        return value + 100
      } else {
        return value
      }
    },
    initChat() {
      this.disposeEcharts()
      const { xAxisData, seriesData } = this.chartData
      if (xAxisData.length <= 0 || seriesData.length <= 0) return
      const series = []
      const yAxis = {
        left: JSON.parse(JSON.stringify(baseYAxisConfig)),
        right: JSON.parse(JSON.stringify(baseYAxisConfig))
      }
      const seriesUnit = {}
      seriesData.forEach((serie, index) => {
        const isYLeftAxis = index === 0
        const serieItem = {
          smooth: true,
          name: `${serie.name}${getUnitFromLevel(this.unitLevel, serie.dataType)}`,
          type: 'line',
          yAxisIndex: isYLeftAxis ? 0 : 1,
          data: serie.tendencyData,
          symbol: 'circle',
          symbolSize: 6
        }
        let maxSerieValue, minSerieValue
        if (Array.isArray(serie.tendencyData) && serie.tendencyData.length > 0) {
          maxSerieValue = Math.max(...serie.tendencyData)
          minSerieValue = Math.min(...serie.tendencyData)
        }
        // 处理值相同时x轴刻度
        if (maxSerieValue === minSerieValue) {
          if (minSerieValue === 0) {
            maxSerieValue++
          } else {
            minSerieValue = 0
          }
        } else {
          if (serie.dataType === 'number') {
            maxSerieValue = maxSerieValue + ((maxSerieValue - minSerieValue) / 6)
            if (minSerieValue >= 0) {
              minSerieValue = minSerieValue * 0.5
            } else {
              minSerieValue = minSerieValue * 1.5
            }
          }
          if (serie.dataType === 'percent' || serie.dataType === 'pt') {
            maxSerieValue = maxSerieValue + 0.05
            minSerieValue = minSerieValue - 0.05
          }
          if (serie.dataType === 'person') {
            maxSerieValue = maxSerieValue + ((maxSerieValue - minSerieValue) / 6)
            if (minSerieValue !== 0) {
              minSerieValue = minSerieValue * 0.5
            }
          }
        }
        series.push(serieItem)
        seriesUnit[serieItem.name] = serie.dataType
        yAxis[isYLeftAxis ? 'left' : 'right'].max = maxSerieValue
        yAxis[isYLeftAxis ? 'left' : 'right'].min = minSerieValue
        yAxis[isYLeftAxis ? 'left' : 'right'].interval = (maxSerieValue - minSerieValue) / 4
        yAxis[isYLeftAxis ? 'left' : 'right'].axisLabel.formatter = (value, index) => {
          return dataFormatWidthUnitLevel(value, serie.dataType, this.unitLevel, value === 0 ? 0 : 1)
        }
      })
      const legendData = series.map(s => s.name)
      const option = {
        tooltip: {
          trigger: 'axis',
          borderWidth: 0,
          axisPointer: {
            type: 'shadow'
          },
          textStyle: {
            color: '#e9e9ed'
          },
          extraCssText:'z-index: 0',
          backgroundColor: '#393f52',
          formatter: params => {
            const name = params[0].name
            let html = `${name}<br/>`
            params.forEach((param, index) => {
              let primaryValue = '-', secondaryValue = '-'
              if (_.isNumber(param.value)) {
                if (index === 0) {
                  primaryValue = dataFormatWidthUnitLevel(param.value, seriesUnit[param.seriesName], this.unitLevel, param.value === 0 ? 0 : 1)
                } else {
                  secondaryValue = dataFormat(param.value, seriesUnit[param.seriesName], 1)
                }
              }
              html += `<div style="display:flex;">
              <div style="margin-right: 20px;">${param.marker}${param.seriesName}</div>
              <div style="margin-left: auto;">
              ${index === 0 ? primaryValue : secondaryValue}
              ${getUnitFromLevel(this.unitLevel, seriesUnit[param.seriesName])}
              </div>
              </div>`
            })
            return html
          },
          position: function(pos, params, dom, rect, size) {
            // 鼠标在左侧时 tooltip 显示到右侧，鼠标在右侧时 tooltip 显示到左侧。
            var obj = { top: 60 }
            obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5
            return obj
          }
        },
        color: ['#FFA925', '#EEF5FF'],
        legend: {
          itemWidth: 6,
          itemHeight: 6,
          icon: 'rect',
          data: legendData,
          left: 'left',
          textStyle: {
            color: '#D5D5D8'
          }
        },
        grid: {
          left: '0',
          right: '15',
          bottom: '3%',
          top: 40,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          boundaryGap: false,
          data: xAxisData,
          axisLabel: {
            margin: 15,
            interval: 0,
            padding: [0, 8, 0, 0],
            // rotate: 55,
            color: '#D5D5D8',
            formatter: (value, index) => {
              let result = ''
              if (this.currentDate === 'year') {
                result = index % 3 === 0 ? value.substring(0, 7) : ''
              } else if (this.currentDate === 'month' && xAxisData.length > 7) {
                if (index === xAxisData.length - 1) {
                  result = value.substring(5, 10)
                } else {
                  result = index % 6 === 0 ? value.substring(5, 10) : ''
                }
              } else {
                result = value.substring(5, 10)
              }
              return result
            }
          }
        },
        // dataZoom: xAxisData.length > 10 ? echartDataZoom : [],
        yAxis: seriesData.length === 1 ? [yAxis.left] : [yAxis.left, yAxis.right],
        series: series
      }
      const chartDom = this.$refs.chart
      // const chartDom = document.getElementById('line-chart')
      this.$nextTick(() => {
        this.lineChart = echarts.init(chartDom)
        this.lineChart.setOption(option)
      })
    },
    openPicker() {
      this.showPicker = true
    },
    closePicker() {
      this.showPicker = false
    }
  },
  computed: {
    chartData() {
      return {
        xAxisData: this.xAxis,
        seriesData: this.data
      }
    },
    currentDate: function() {
      return this.dateType
    },
    currentDateText: function() {
      return this.dateColumns.find(item => item.code === this.currentDate).text
    },
    noData: function() {
      return this.xAxis.length === 0
    }
  },
  watch: {
    chartData() {
      this.initChat()
    }
  },
  destroyed() {
    this.disposeEcharts()
  },
}
</script>

<style lang="scss" scoped>
.echartsLine_container {
  .filters {
    display: flex;
    align-items: center;
    margin-top: 16px;
    margin-bottom: 10px;
    .filter_text {
      font-size: 14px;
    }
    .filter_btn {
      height: 28px;
      background-color: #393f52;
      border: none;
      margin-left: auto;
    }
  }
  .chart_container {
    height: 180px;
  }
  .baseDataline {
    height: 1px;
    margin: 16px -20px 12px -20px;
    width: 375px;
    background-color: $light-bc;
  }
  .no-data {
    font-size: 12px;
    display: flex;
    height: 78px;
    align-items: center;
    justify-content: center;
    color: #a3a5ac;
  }

}
</style>
